/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.lcfgly.Plug;

import com.lcfgly.DatabaseFactory.DataFactoryInterface;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

/**
 * datatable插件数据调用
 * @author lcfgly
 */
public abstract class DataTable{
    
    final DataFactoryInterface data;
    Logger log=Logger.getLogger("SqlError");

    public DataTable(DataFactoryInterface data) {
        this.data = data;
    }
    
    /**
     * DataTable数据处理
     * @param request 请求的内容
     * @param table 操作的表
     * @param select 搜索字段
     * @param join 附加表
     * @param where 条件
     * @param order 排序
     * @param out
     * @return
     * @throws SQLException 
     */
    public Map GetDataForDataTable(HttpServletRequest request,String table,String select,String join,String where,String order,Map out)throws SQLException
    {
        Map<String,Object> reList=new HashMap<String, Object>();
        Map result=GetDataTableData(request,table,out);
        String sql;
        String sql2="SELECT count(1) FROM "+table;
        Object[] res=null;
        if(select == null)
            sql="SELECT * FROM "+table;
        else
            sql="SELECT "+select+" FROM "+table;
        if(!(join ==null)){
            sql+=join;
            sql2+=join;
        }
        if(where != null && result.get("where") != null){
            sql+=" WHERE "+where+" AND ("+result.get("where")+")";
            sql2+=" WHERE "+where+" AND ("+result.get("where")+")";
        }else if( where != null && result.get("where") == null){
            sql+=" WHERE "+where;
            sql2+=" WHERE "+where;
        }else if(where == null && result.get("where") != null){
            sql+=" WHERE "+result.get("where");
            sql2+=" WHERE "+result.get("where");
        }
        if(result.get("params") != null){
            List re=(List)result.get("params");
            res=new Object[re.size()];
            int i=0;
            for(Object r:re){
                res[i++]=r;
            }
        }
        if (!(result.get("limit") == null)) {
            sql += " LIMIT  " + result.get("limit");
        }
        try{
           reList.put("iTotalDisplayRecords", data.Getrowsnum(sql2,res));
        }catch(SQLException e){
            log.error(e);
            reList.put("iTotalDisplayRecords", 0);
        }
        try{
           reList.put("aaData", data.rowsWithOutObject(sql,res));
        }catch(SQLException e){
            log.error(e);
            reList.put("aaData","");
        }
        return reList;
    }
    
    /**
     * 按照DataTable提交的数据格式解析数据
     * @param request
     * @return 
     */
    private Map  GetDataTableData(HttpServletRequest request,String table,Map out)
    {
        if(out==null)
            out=new HashMap();
        Map result=new HashMap();
        if(!request.getParameter("iSortCol_0").isEmpty())
        {
            //排序列名
            String col=request.getParameter("mDataProp_"+request.getParameter("iSortCol_0"));
            //排序方式
            String coltp=request.getParameter("sSortDir_0");
            result.put("order", col+" "+coltp);
        }
        if(!request.getParameter("sSearch").isEmpty())
        {
            //获取表格列数
            int iColumns=Integer.valueOf(request.getParameter("iColumns"));
            String where="";
            List<Object> whereList=new ArrayList<Object>();
            for(int i=0;i<iColumns;i++)
            {
                if(request.getParameter("mDataProp_"+i).isEmpty())
                    continue;
                if(out.get(request.getParameter("mDataProp_"+i)) != null)
                    where+=" "+out.get(request.getParameter("mDataProp_"+i))+" like ?  or";
                else
                    where+=" "+table+"."+request.getParameter("mDataProp_"+i)+" like ?  or";
                whereList.add("%"+request.getParameter("sSearch")+"%");
            }
            if(where.length()>2)
                where =where.substring(0, where.length()-2);
            result.put("where", where);
            result.put("params", whereList);
        }
        if(request.getParameter("iDisplayStart").isEmpty() )
            result.put("limit", request.getParameter("iDisplayLength"));
        else
           result.put("limit", request.getParameter("iDisplayStart")+","+request.getParameter("iDisplayLength"));
        return result;
    }
    
}
